﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using System.Management;
using System.IO;

namespace TfsExtensions.Build.Activities
{
    public sealed class CopyFromSandCastleInstallation : CodeActivity
    {
        [RequiredArgument]
        public InArgument<string> SandcastlePresentationFolder { get; set; }

        [RequiredArgument]
        public InArgument<string> WorkingFolder { get; set; }

        public OutArgument<System.UInt16> copyResult { get; set; }

        protected override void Execute(CodeActivityContext context)
        {
            DirectoryInfo source = new DirectoryInfo(string.Format(@"{0}\icons", this.SandcastlePresentationFolder.Get(context)));
            DirectoryInfo target = new DirectoryInfo(string.Format(@"{0}\icons", this.WorkingFolder.Get(context)));

            this.CopyAll(source, target);

            source = new DirectoryInfo(string.Format(@"{0}\scripts", this.SandcastlePresentationFolder.Get(context)));
            target = new DirectoryInfo(string.Format(@"{0}\scripts", this.WorkingFolder.Get(context)));

            this.CopyAll(source, target);

            source = new DirectoryInfo(string.Format(@"{0}\styles", this.SandcastlePresentationFolder.Get(context)));
            target = new DirectoryInfo(string.Format(@"{0}\styles", this.WorkingFolder.Get(context)));

            this.CopyAll(source, target);
        }

        private void CopyAll(DirectoryInfo source, DirectoryInfo target)
        {
            // Check if the target directory exists, if not, create it.
            if (Directory.Exists(target.FullName) == false)
            {
                Directory.CreateDirectory(target.FullName);
            }

            // Copy each file into it’s new directory.
            foreach (FileInfo fi in source.GetFiles())
            {
                fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
            }

            // Copy each subdirectory using recursion.
            foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
            {
                DirectoryInfo nextTargetSubDir =
                    target.CreateSubdirectory(diSourceSubDir.Name);
                CopyAll(diSourceSubDir, nextTargetSubDir);
            }
        }
    }
}
